import type {
  TableColumnProps,
  ProSaasTableExposeType,
  // TableProps,
  ColumnsSpanType
} from '~/components/ProSaasTable/typings'
import type { DeviceTaskStatusEnumType } from '~/store/monitorManagement/loopMonitorBox/typings'
import type { DeviceApplicationDataItemType, DeviceApplicationStateType } from './typings'
import { defineComponent, ref, reactive, onMounted, nextTick } from 'vue'
import { useStore } from 'vuex'
import {
  ElCard,
  ElButton,
  ElSpace,
  ElLink,
  ElFormItem,
  ElInput,
  ElSelect,
  ElOption,
  ElMessageBox,
  ElMessage
} from 'element-plus'
import AliIcon from '~/components/AliIocn'
import SaasTitle from '~/components/SaasTitle'
import ProSaasTable from '~/components/ProSaasTable'
import ColorfulBadge from '~/components/ColorfulBadge'
import ApplicationRecordModal from './DeviceApplicationUseComponents/ApplicationRecordModal'
import CallTestResultsModal from './DeviceApplicationUseComponents/CallTestResultsModal'
import ExecutionLogModal from './DeviceApplicationUseComponents/ExecutionLogModal'
import useVuexGetters from '~/hooks/useVuexGetters'
import { handleTrim } from '~/utils/util'
import styles from '../../index.module.scss'

export default defineComponent({
  name: 'DeviceApplicationComponent',
  props: ['detail', 'goBack'],
  setup(props) {
    const store = useStore()
    // const filterSettingsRef = ref<
    //   Record<string, ColumnsSpanType & { use: number; useId?: string }>
    // >({})
    const proSaasTableRef = ref<ProSaasTableExposeType>()
    const formValues = reactive<DeviceApplicationDataItemType>({})
    const state = reactive<DeviceApplicationStateType>({})
    const deviceApplicationState = useVuexGetters('deviceApplication', [
      'deviceTaskStatusSelectList',
      'deviceTaskStatusEnum'
    ])

    // 按回车搜索列表
    const handleKeyDownEnterSearchList = (evt: Event | KeyboardEvent) => {
      if ((evt as KeyboardEvent).key === 'Enter') nextTick(proSaasTableRef.value!?.toSearch)
    }

    // 根据变更查询列表数据
    const handleChangeValueActionSearchList = () => {
      nextTick(proSaasTableRef.value!?.toSearch)
    }

    // 移出选中数据
    const handleRemoveSelectData = async (record?: DeviceApplicationDataItemType) => {
      if (!record && !proSaasTableRef.value!.selecteds?.length) {
        ElMessage({ type: 'warning', message: '请至少选中一条数据进行操作' })
        return
      }
      const params =
        record?.id || proSaasTableRef.value!.selecteds?.map?.((item) => item!?.id)?.join(',')
      const res = await store.dispatch('deviceApplication/RemoveDeviceApplicationInfo', {
        groupLoopIds: params
      })
      if (res?.code === 200) {
        ElMessage({ type: 'success', message: '移出成功，清除任务已下发，请耐心等待设备响应' })
        handleChangeValueActionSearchList()
      }
    }

    // 应用选中数据
    const handleApplySelectData = async (record?: DeviceApplicationDataItemType) => {
      if (!record && !proSaasTableRef.value!.selecteds?.length) {
        ElMessage({ type: 'warning', message: '请至少选中一条数据进行操作' })
        return
      }
      const params =
        record?.id || proSaasTableRef.value!.selecteds?.map?.((item) => item!?.id)?.join(',')
      const res = await store.dispatch('deviceApplication/ApplyDeviceApplicationInfo', {
        groupLoopIds: params
      })
      if (res?.code === 200) {
        ElMessage({ type: 'success', message: '操作成功' })
        handleChangeValueActionSearchList()
      }
    }

    // 召测所选设备
    const handleCallTestSelectData = async () => {
      if (!proSaasTableRef.value!.selecteds?.length) {
        ElMessage({ type: 'warning', message: '暂时只支持单台设备召测' })
        return
      }
      const deviceId = proSaasTableRef.value!.selecteds[0]?.deviceId
      if (!proSaasTableRef.value!.selecteds?.every((item) => item.deviceId === deviceId)) {
        ElMessage({ type: 'warning', message: '暂时只支持单台设备召测' })
        return
      }
      handleSetVisibleData('callForTest', proSaasTableRef.value!.selecteds[0])
    }

    // 根据传入参数判断展示何种类型弹框并设置值
    const handleSetVisibleData = (
      visibleType: DeviceApplicationStateType['visibleType'],
      record?: DeviceApplicationStateType['record']
    ) => {
      state.visibleType = visibleType
      state.record = record || {}
    }

    // 清空visible相关数据并查询列表
    const handleClearVisibleData = () => {
      state.visibleType = undefined
      state.record = undefined
      handleChangeValueActionSearchList()
    }

    // 查看失败信息
    const handleOpenErrorReasonModal = (record?: DeviceApplicationDataItemType) => {
      ElMessageBox.alert(record?.reason, '失败原因', {
        showConfirmButton: false
      })
    }

    // 过滤table数据
    const handleFilterTableData = (
      filterData: DeviceApplicationDataItemType[]
    ): DeviceApplicationDataItemType[] => {
      const filterSettings: Record<string, ColumnsSpanType> = {}
      return filterData.map((item) => {
        if (item?.deviceId && !filterSettings[item?.deviceId]) {
          filterSettings[item?.deviceId] = {
            rowspan: 1,
            colspan: 1
          }
          return {
            ...item,
            filterSettings: filterSettings[item?.deviceId]
          }
        } else {
          if (filterSettings?.[item?.deviceId!]) filterSettings[item.deviceId!].rowspan!++
          return {
            ...item,
            filterSettings: {
              rowspan: 0,
              colspan: 0
            }
          }
        }
      })
    }
    // const handleFilterTableData = (
    //   filterData: DeviceApplicationDataItemType[]
    // ): DeviceApplicationDataItemType[] => {
    //   filterSettingsRef.value = {}
    //   const arr = filterData.map((item) => {
    //     if (item?.deviceId && !filterSettingsRef.value[item?.deviceId]) {
    //       filterSettingsRef.value[item?.deviceId] = {
    //         rowspan: 1,
    //         colspan: 1,
    //         use: 0
    //       }
    //     } else if (filterSettingsRef.value?.[item?.deviceId!])
    //       filterSettingsRef.value[item.deviceId!].rowspan!++

    //     return item
    //   })

    //   return arr
    // }

    // 根据数据来决定返回结果
    // const handleSpanMethodTableData: TableProps<DeviceApplicationDataItemType>['spanMethod'] = ({
    //   row,
    //   column
    // }) => {
    //   const spanSetting = {
    //     rowspan: 1,
    //     colspan: 1
    //   }
    //   if (column.property === 'deviceName') {
    //     // 这里因为渲染不止一次遍历 所以要记下首次出现的id 然后做匹配
    //     if (
    //       filterSettingsRef.value?.[row.deviceId!]?.use === 0 ||
    //       filterSettingsRef.value?.[row.deviceId!]?.useId === row.id
    //     ) {
    //       filterSettingsRef.value[row.deviceId!].useId = row.id
    //       filterSettingsRef.value[row.deviceId!].use++
    //       spanSetting.colspan = filterSettingsRef.value?.[row.deviceId!].colspan || 1
    //       spanSetting.rowspan = filterSettingsRef.value?.[row.deviceId!].rowspan || 1
    //     } else if (filterSettingsRef.value?.[row.deviceId!]) {
    //       spanSetting.colspan = 0
    //       spanSetting.rowspan = 0
    //     }
    //   }
    //   return spanSetting
    // }

    onMounted(() => {
      if (!deviceApplicationState.deviceTaskStatusSelectList.value?.length) {
        store.dispatch('deviceApplication/GetDeviceTaskStatusSelectList')
      }
    })

    const columns: TableColumnProps<DeviceApplicationDataItemType>[] = [
      {
        label: '设施名称',
        prop: 'deviceName',
        minWidth: 180
      },
      {
        label: '回路开关',
        prop: 'loopName',
        minWidth: 180
      },
      {
        label: '所属工区',
        prop: 'workAreaName',
        minWidth: 180
      },
      {
        label: '执行状态',
        prop: 'taskStatus',
        enumValues: deviceApplicationState.deviceTaskStatusEnum,
        minWidth: 180,
        render: (option, value) => (
          <ColorfulBadge
            enumKey={option.row.taskStatus!}
            options={{ info: 0, success: 2, warning: 3 }}
          >
            {option?.row?.taskStatus === 3 && option?.row?.reason ? (
              <ElLink
                type="primary"
                underline={false}
                onClick={() => handleOpenErrorReasonModal(option?.row)}
              >
                {value}
              </ElLink>
            ) : (
              value
            )}
          </ColorfulBadge>
        )
      },
      {
        label: '执行时间',
        prop: 'taskTime',
        minWidth: 220,
        sortable: true
      },
      {
        label: '操作',
        prop: 'options',
        align: 'center',
        minWidth: 360,
        render: ({ row }) => (
          <ElSpace wrap>
            <ElLink
              type="primary"
              icon={<AliIcon type="icon-yingyong1" />}
              onClick={() => handleApplySelectData(row)}
            >
              应用
            </ElLink>
            <ElLink
              type="primary"
              icon={<AliIcon type="icon-zhaoce1" />}
              onClick={() => handleSetVisibleData('callForTest', row)}
            >
              召测
            </ElLink>
            <ElLink
              type="warning"
              icon={<AliIcon type="icon-yichu1" />}
              onClick={() => handleRemoveSelectData(row)}
            >
              移出
            </ElLink>
            <ElLink
              type="primary"
              icon={<AliIcon type="icon-lishirenwu1" />}
              onClick={() => handleSetVisibleData('applicationRecord', row)}
            >
              应用记录
            </ElLink>
            <ElLink
              type="primary"
              icon={<AliIcon type="icon-zhihangrizhi1" />}
              onClick={() => handleSetVisibleData('executionLog', row)}
            >
              执行日志
            </ElLink>
          </ElSpace>
        )
      }
    ]

    return () => (
      <ElCard
        shadow="never"
        class="covered-with-content"
        v-slots={{
          header: () => (
            <section class={styles['loop-group-tree-header']}>
              <SaasTitle type="primary">设备应用</SaasTitle>
              <ElButton text type="primary" onClick={props.goBack}>
                返回上一级&nbsp;
                <AliIcon type="icon-fanhuishangyiji" />
              </ElButton>
            </section>
          )
        }}
      >
        <ProSaasTable<DeviceApplicationDataItemType>
          ref={proSaasTableRef}
          columns={columns}
          rowKey="id"
          hasSelection
          useGridLayout={false}
          filterTableDataMethod={handleFilterTableData}
          // spanMethod={handleSpanMethodTableData}
          spanMethod={({ row, column }) =>
            column.property === 'deviceName' ? row.filterSettings! : { rowspan: 1, colspan: 1 }
          }
          defaultSort={{ prop: 'taskTime', order: 'descending' }}
          dispatchType="deviceApplication/GetDeviceApplicationList"
          searchParams={{
            taskId: props.detail?.id,
            name: formValues.deviceName && handleTrim(formValues.deviceName)
          }}
          searchFormProps={{
            model: formValues
          }}
          searchformResponsiveCol={[
            <ElFormItem key="deviceName" prop="deviceName">
              <ElInput
                v-model={formValues.deviceName}
                placeholder="设备名称"
                clearable
                onKeydown={handleKeyDownEnterSearchList}
              />
            </ElFormItem>,
            <ElFormItem key="taskStatus" prop="taskStatus">
              <ElSelect
                v-model={formValues.taskStatus}
                placeholder="执行状态"
                clearable
                onChange={handleChangeValueActionSearchList}
              >
                {deviceApplicationState.deviceTaskStatusSelectList.value?.map(
                  (item: DeviceTaskStatusEnumType) => (
                    <ElOption key={item?.dictKey} label={item?.dictValue} value={item?.dictKey!} />
                  )
                )}
              </ElSelect>
            </ElFormItem>
          ]}
        >
          <ElSpace>
            <ElButton
              type="primary"
              icon={<AliIcon type="icon-yichu1" />}
              onClick={() => handleRemoveSelectData()}
            >
              移出设备
            </ElButton>
            <ElButton
              type="primary"
              icon={<AliIcon type="icon-yingyong1" />}
              onClick={() => handleApplySelectData()}
            >
              批量应用
            </ElButton>
            <ElButton
              type="primary"
              icon={<AliIcon type="icon-zhaoce1" />}
              onClick={() => handleCallTestSelectData()}
            >
              召测设备
            </ElButton>
          </ElSpace>
        </ProSaasTable>
        {/* <CallTestResultsModal visible={state.visibleType === 'callForTest'} detail={state.record} doClose={handleClearVisibleData} /> */}
        {state.visibleType === 'callForTest' && (
          <CallTestResultsModal detail={state.record} doClose={handleClearVisibleData} />
        )}
        {state.visibleType === 'applicationRecord' && (
          <ApplicationRecordModal detail={state.record} doClose={handleClearVisibleData} />
        )}
        {state.visibleType === 'executionLog' && (
          <ExecutionLogModal detail={state.record} doClose={handleClearVisibleData} />
        )}
      </ElCard>
    )
  }
})
